<?php

namespace App\Http\Controllers\Wx;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\UserAddress;
use App\Http\Requests\ApiRequest;

class UserAddressController extends Controller
{
    public function index(ApiRequest $request)
    {
    	$rs['status'] = true;
    	$where['user_id'] = $request->user_id; 
    	$list = UserAddress::where($where)
                            ->orderBy('is_default','desc')
                            ->paginate(10);
    	$rs['data'] = $list;      
        return response()->json($rs);
    }

    public function info(ApiRequest $request)
    {
    	$rs['status']      = true;        
        $where['user_id'] = $request->user_id; 
        $where['id'] = $request->id;
        $data = UserAddress::where($where)->first(); 
        $rs['data'] = $data;      
        return response()->json($rs);
    }

    public function store(ApiRequest $request)
    {
    	$rs['status']      = true;         
        $data = $request->pure();
        if($data['is_default']==1) {
        	$where['user_id'] = $request->user_id;      
        	UserAddress::where($where)->update(['is_default'=>0]);
        }
        $flag = UserAddress::create($data); 
        $rs['data'] = $flag;      
        return response()->json($rs);
    }

    public function update(ApiRequest $request)
    {
    	$rs['status']      = true;       
        $where['id'] = $request->id;
        $data = $request->pure();
        if($data['is_default']==1) {
            $where['user_id'] = $request->user_id;      
            UserAddress::where($where)->update(['is_default'=>0]);
        }
        $flag = UserAddress::where($where)->update($data); 
        $rs['data'] = $flag;      
        return response()->json($rs);
    }

    public function delete(ApiRequest $request)
    {
    	$rs['status']      = true;        
        $where['user_id'] = $request->user_id; 
        $where['id'] = $request->id;
        $data = UserAddress::where($where)->delete(); 
        $rs['data'] = $data;      
        return response()->json($rs);
    }

    public function setdefault(ApiRequest $request)
    {
    	$rs['status']      = true;       
        $where['user_id'] = $request->user_id;      
        UserAddress::where($where)->update(['is_default'=>0]);
        $where['id'] = $request->id;
        $flag = UserAddress::where($where)->update(['is_default'=>1]);
        if(!$flag) {
        	$rs['status'] = false;
        	$rs['msg'] = '操作失败';
        	return response()->json($rs);

        }
        $rs['data'] = $flag;      
        return response()->json($rs);
    }
}
